// const jwt = require('koa-jwt')
const jwt = require('jsonwebtoken')
const bcrypt = require('bcryptjs')
const user = require('../models/user.js')

// 通过用户ID，获取用户信息
const getUserInfo = async (ctx, next) => {
  const id = ctx.params.id
  const result = await user.getUserById(id)
  ctx.response.body = result
}

// 登陆
const postUserAuth = async (ctx, next) => {
  const data = ctx.request.body
  console.log('request-body:', data)
  const userInfo = await user.getUserByName(data.name)
  // console.log('userinfo:',userInfo)
  if (userInfo != null) {
    if (!bcrypt.compareSync(data.password, userInfo.password)) {
      ctx.body = {
        success: false,
        info: '密码错误'
      }
    } else {
      const userToken = {
        name: userInfo.user_name,
        id: userInfo.id
      }
      const secret = 'vue-koa-todolist'
      const token = jwt.sign(userToken, secret)
      ctx.body = {
        success: true,
        token: token
      }
    }
  } else {
    ctx.body = {
      success: false,
      info: '用户不存在'
    }
  }
}
module.exports = {
  getUserInfo,
  postUserAuth
}
